<template>
  <div
    v-for="event in editorStore.currentComponent!.events"
    :key="event.type"
    class="event"
  >
    <div class="event-header">
      <span>{{ event.typeName }}</span>
      <el-button link type="primary" @click="showEdit(event.type)">
        编辑
      </el-button>
    </div>
    <span>async function {{ event.handlerName }}() {</span>
    <div class="editor-container">
      <CodeEditor
        v-model="event.handler"
        :options="{ readOnly: true, lineNumbers: 'off' }"
      />
    </div>
    <span>}</span>
  </div>

  <el-dialog v-model="visible" title="编辑事件">
    <el-tabs type="card" v-model="activeName">
      <el-tab-pane
        v-for="event in editEvents"
        :key="event.type"
        :label="event.typeName"
        :name="event.type"
      >
        <div class="edit-container">
          <span>async function {{ event.handlerName }}() {</span>
          <div class="editor-container">
            <CodeEditor
              v-model="event.handler"
              :options="{ lineNumbers: 'off' }"
            />
          </div>
          <span>}</span>
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { cloneDeep } from "lodash-es";
import useEditorStore from "@/store/modules/editor";
import type { EventType } from "@/materials/index.d";

defineOptions({
  name: "Events",
});

const editorStore = useEditorStore();

const editEvents = ref<EventType[]>([]);
const activeName = ref("");

const visible = ref(false);
// 显示对话框
const showEdit = (type: string) => {
  visible.value = true;
  editEvents.value = cloneDeep(editorStore.currentComponent!.events);
  activeName.value = type;
};
// 取消
const cancel = () => {
  visible.value = false;
};
// 确定
const submit = () => {
  visible.value = false;
  editorStore.currentComponent!.events = editEvents.value;
};
</script>

<style scoped lang="scss">
.event {
  padding: 10px;
  font-size: 14px;
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-container {
  height: 100px;
}

:deep(.el-tabs__nav) {
  width: auto !important;
}

.edit-container {
  font-size: 16px;
  margin: 10px 0;
}
</style>
